package oas.web;

import oas.db.UserRepository;
import oas.db.WorkcellRepository;
import oas.domain.User;
import oas.domain.Workcell;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 系统主页面控制类
 *
 * @author liyue
 * @version v1.0.0
 */
@Controller
@RequestMapping("/")
public class HomeController {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private WorkcellRepository workcellRepository;

    private final static Log log = LogFactory.getLog(HomeController.class);

    /**
     * 首页
     *
     * @return 首页视图
     */
    @RequestMapping(method = RequestMethod.GET)
    public String home(HttpSession session) {

        User user = (User) session.getAttribute("user");

//        if (user != null && user.getUsername() != null) {
//            if ("User".equals(user.getRole())) {
//                return "userHome";
//            }
//            if ("Manager".equals(user.getRole())) {
//                return "adminHome";
//            }
//        }

        return "redirect:/logincookie";
    }

    /**
     * 登录页面
     *
     * @return 登录页面视图
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String showLogin() {
        return "login";
    }

    /**
     * 登录
     *
     * @param userName 用户名
     * @param password 密码
     * @param session  HTTP Session
     * @return 登录结果视图
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(@RequestParam(value = "userName", defaultValue = "") String userName,
                        @RequestParam(value = "password", defaultValue = "") String password,
                        HttpSession session, HttpServletResponse response) {
        //User user = userRepository.findByUserName(userName, password);

        log.debug(password + ", " + Base64.getEncoder().encodeToString("123456".getBytes()));
        byte[] decodedPwd = Base64.getDecoder().decode(password);
        password = new String(decodedPwd);
        log.debug(password);
        User user = userRepository.findByUserName(userName, password);
        if (user != null) {
            Workcell workcell = user.getWorkcell();
            workcell.setChildWorkcells(workcellRepository.findWorkcells(user.getWorkcell()));
            user.setWorkcell(workcell);
            session.setAttribute("user", user);
            session.setMaxInactiveInterval(1 * 24 * 60 * 60 * 1000);
            Cookie usernameCookie = new Cookie("username", user.getUsername());
            response.addCookie(usernameCookie);

            // Cookie[] cookies = request.getCookies();
            // System.out.println("外部的SessionId:"+session.getId());

            if ("User".equals(user.getRole())) {

                return "redirect:/";
            }

            if ("Manager".equals(user.getRole())) {
                return "redirect:/";
            }
        }


        return "loginError";
    }

    /**
     * 自动登录请求
     *
     * @param userName
     * @param password
     * @param session
     * @return
     */
    @RequestMapping("/logincookie")
    public String autoLogin(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("进入了自动登录的Controller！");
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return "redirect:/login";
        }
        HttpSession session = request.getSession(false);
        String sessionId = session.getId();

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("JSESSIONID")) {
                if (!cookie.getValue().equals(sessionId)) {
                    return "redirect:/login";
                }
            }
        }

        for (Cookie cookie2 : cookies) {
            if (cookie2.getName().equals("username") && cookie2.getValue() != null) {
                String cookieUsername = cookie2.getValue();
                try {
                    User user = userRepository.findByUserName(cookieUsername);
                    User userSession = (User) session.getAttribute("user");
                    //String realPassword = user.get;
                    if (userSession.getUsername().equals(user.getUsername()) && user.getRole()
                            .equals("Manager")) {
                        return "adminHome";
                    } else if (userSession.getUsername().equals(user.getUsername()) && user.getRole()
                            .equals("User")) {
                        return "userHome";
                    } else {
                        return "redirect:/login";
                    }

                } catch (NullPointerException e) {
                    return "redirect:/login";
                }

            }
        }

        return "redirect:/login";
    }

    @RequestMapping(value = "logout", method = GET)
    public String managerLogout(HttpSession session, HttpServletResponse response) {
        //删除cookie
        Cookie usernameCookie = new Cookie("username", "");
        usernameCookie.setMaxAge(0);
        usernameCookie.setPath("/");
        response.addCookie(usernameCookie);
        session.removeAttribute("user");
        session.invalidate();
        return "redirect:/";
    }
}
